#include <iostream>
#include <pthread.h>
#include <unistd.h>

int ticket = 100;

pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
void *Routine(void *args)
{
    char *id = static_cast<char *>(args);
    while (1)
    {
        pthread_mutex_lock(&lock);
        if (ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket:%d\n", id, ticket);
            ticket--;
            pthread_mutex_unlock(&lock);
        }
        else
        {
            pthread_mutex_unlock(&lock);
            break;
        }
    }
    return nullptr;
}

int main()
{

    pthread_t t1, t2, t3, t4;
    pthread_create(&t1, nullptr, Routine, (void *)"pthread-1");
    pthread_create(&t2, nullptr, Routine, (void *)"pthread-2");
    pthread_create(&t3, nullptr, Routine, (void *)"pthread-3");
    pthread_create(&t4, nullptr, Routine, (void *)"pthread-4");

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);

    return 0;
}
